// Package repository internal/repository/post_repository.go
package repository

import (
	"errors"
	"gorm.io/gorm"
	"gozrd-admin-api/internal/entity/model"
	"time"
)

var (
	PostCodeExist = errors.New("岗位编码已存在")
	PostNameExist = errors.New("岗位名称已存在")
)

// IPostRepository 岗位仓库接口
type IPostRepository interface {
	GetSysPostByCode(postCode string) (model.SysPost, error)
	GetSysPostByName(postName string) (model.SysPost, error)
	CreateSysPost(post model.SysPost) error
	GetSysPostList(pageNum, pageSize int, postName, postStatus, beginTime, endTime string) ([]model.SysPost, int64, error)
	GetSysPostById(id int) (model.SysPost, error)
	UpdateSysPost(post model.SysPost) (model.SysPost, error)
	DeleteSysPostById(id int) error
	BatchDeleteSysPost(ids []int) error
	UpdateSysPostStatus(id int, status int) error
	QuerySysPostList() ([]model.SysPost, error)
}

// PostRepository 岗位仓库实现
type PostRepository struct {
	db *gorm.DB
}

// NewPostRepository 创建岗位仓库
func NewPostRepository(db *gorm.DB) IPostRepository {
	return &PostRepository{
		db: db,
	}
}

// GetSysPostByCode 根据编码查询岗位
func (r *PostRepository) GetSysPostByCode(postCode string) (model.SysPost, error) {
	var post model.SysPost
	err := r.db.Where("post_code = ?", postCode).First(&post).Error
	return post, err
}

// GetSysPostByName 根据名称查询岗位
func (r *PostRepository) GetSysPostByName(postName string) (model.SysPost, error) {
	var post model.SysPost
	err := r.db.Where("post_name = ?", postName).First(&post).Error
	return post, err
}

// CreateSysPost 新增岗位
func (r *PostRepository) CreateSysPost(post model.SysPost) error {
	// 检查岗位编码是否已存在
	existingPostByCode, err := r.GetSysPostByCode(post.PostCode)
	if err != nil && err != gorm.ErrRecordNotFound {
		return err
	}
	if existingPostByCode.ID > 0 {
		return PostCodeExist
	}

	// 检查岗位名称是否已存在
	existingPostByName, err := r.GetSysPostByName(post.PostName)
	if err != nil && err != gorm.ErrRecordNotFound {
		return err
	}
	if existingPostByName.ID > 0 {
		return PostNameExist
	}

	// 设置创建时间
	post.CreateTime = time.Now()

	// 创建岗位
	return r.db.Create(&post).Error
}

// GetSysPostList 分页查询岗位列表
func (r *PostRepository) GetSysPostList(pageNum, pageSize int, postName, postStatus, beginTime, endTime string) ([]model.SysPost, int64, error) {
	var posts []model.SysPost
	var count int64

	db := r.db.Model(&model.SysPost{})

	// 添加查询条件
	if postName != "" {
		db = db.Where("post_name = ?", postName)
	}
	if postStatus != "" {
		db = db.Where("post_status = ?", postStatus)
	}
	if beginTime != "" && endTime != "" {
		db = db.Where("create_time BETWEEN ? AND ?", beginTime, endTime)
	}

	// 获取总数
	err := db.Count(&count).Error
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).
		Order("create_time desc").
		Find(&posts).Error

	return posts, count, err
}

// GetSysPostById 根据id查询岗位
func (r *PostRepository) GetSysPostById(id int) (model.SysPost, error) {
	var post model.SysPost
	err := r.db.First(&post, id).Error
	return post, err
}

// UpdateSysPost 修改岗位
func (r *PostRepository) UpdateSysPost(post model.SysPost) (model.SysPost, error) {
	// 使用事务确保原子性
	tx := r.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 查询岗位是否存在
	var existingPost model.SysPost
	if err := tx.First(&existingPost, post.ID).Error; err != nil {
		tx.Rollback()
		return model.SysPost{}, err
	}

	// 更新字段
	existingPost.PostName = post.PostName
	existingPost.PostCode = post.PostCode
	existingPost.PostStatus = post.PostStatus
	if post.Remark != "" {
		existingPost.Remark = post.Remark
	}

	// 保存更改
	if err := tx.Save(&existingPost).Error; err != nil {
		tx.Rollback()
		return model.SysPost{}, err
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		return model.SysPost{}, err
	}

	return existingPost, nil
}

// DeleteSysPostById 根据id删除岗位
func (r *PostRepository) DeleteSysPostById(id int) error {
	return r.db.Delete(&model.SysPost{}, id).Error
}

// BatchDeleteSysPost 批量删除岗位
func (r *PostRepository) BatchDeleteSysPost(ids []int) error {
	return r.db.Where("id IN (?)", ids).Delete(&model.SysPost{}).Error
}

// UpdateSysPostStatus 修改岗位状态
func (r *PostRepository) UpdateSysPostStatus(id int, status int) error {
	return r.db.Model(&model.SysPost{}).Where("id = ?", id).Update("post_status", status).Error
}

// QuerySysPostList 获取岗位列表(用于下拉选择)
func (r *PostRepository) QuerySysPostList() ([]model.SysPost, error) {
	var posts []model.SysPost
	err := r.db.Select("id, post_name").Find(&posts).Error
	return posts, err
}
